import './login.less'
import CAuthCode from '@/components/authCode'
import {SendAuthCode} from '@/components/btn/sendAuthCode'
import CForm from '@/components/form'
import {CImage, IconImg} from '@/components/image'
import {CnBoldSpan, CnNormalP, CnNormalSpan} from '@/components/text'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {FormInstance} from 'ant-design-vue'
import {webLoginGetCode} from '@/api/login'
import useWebSocket from '@/hooks/useWebSocket'
import useQrcode from '@/hooks/useQrcode'
import {message} from '@/libs/global/antDesignVue'

/**手机号验证码登录 */
const UserPhoneLogin = defineComponent({
  name: 'UserPhoneLogin',
  setup() {
    const {router, store} = useGlobalAPI()

    const state = reactive({
      phone: '',
      verfiyCode: ''
    })

    /**提交表单且数据验证成功后回调事件 */
    const handleFormSubmit = async (formRef: FormInstance | undefined) => {
      const res = await store
        .dispatch('login/PHONELOGIN', {
          userPhone: state.phone,
          verfiyCode: state.verfiyCode
        })
        .catch(err => {})
      if (res) {
        router.push('/visualLargeScreen')
      }
    }

    /**获取登录手机号验证码 */
    function getAuthCode() {
      webLoginGetCode({userPhone: state.phone})
        .then(res => {})
        .catch(err => {})
    }

    return () => (
      <CForm
        class='w-318 mt-21 mx-auto'
        v-model={[state, 'model']}
        onFormSubmit={handleFormSubmit}
        onFormReset={() => {}}
        labelCol={{
          span: 0
        }}
        wrapperCol={{
          span: 24
        }}
      >
        <a-form-item class='mb-36' name='userName'>
          <a-input
            v-model={[state.phone, 'value', ['number', 'trim']]}
            class='pl-12 h-40 rounded-2 text-16 border-1 borde-inputLine'
            placeholder='请输入手机号'
          >
            {{
              prefix: () => <IconImg imgName='login-phone' class='w-16 h-16'></IconImg>
            }}
          </a-input>
        </a-form-item>

        <a-form-item class='mb-36' name='dictDesc'>
          <div class='flex justify-between items-center'>
            <a-input
              v-model={[state.verfiyCode, 'value', ['trim']]}
              class='pl-12 h-40 mr-8 rounded-2 text-16'
              placeholder='请输入验证码'
            >
              {{
                prefix: () => <IconImg imgName='login-email' class='w-16 h-16'></IconImg>
              }}
            </a-input>
            <SendAuthCode
              disabled={state.phone === ''}
              onClick={() => {
                if (state.phone) {
                  getAuthCode()
                  return true
                }
                message.warning('请输入手机号')
                return false
              }}
            ></SendAuthCode>
          </div>
        </a-form-item>

        <a-form-item>
          <a-button
            type='primary'
            class='w-full h-40 rounded flex justify-center items-center'
            html-type='submit'
          >
            <CnNormalSpan class='text-white text-16'>登录</CnNormalSpan>
          </a-button>
        </a-form-item>
      </CForm>
    )
  }
})

/**账号密码登录 */
const UserAccountLogin = defineComponent({
  name: 'UserAccountLogin',
  setup() {
    const {router, store} = useGlobalAPI()

    const state = reactive({
      platFormUserName: '',
      platFormUserPass: '',
      authCode: '',
      inputAuthCode: ''
    })

    /**提交表单且数据验证成功后回调事件 */
    const handleFormFinish = async (formRef: FormInstance | undefined) => {
      console.log(state.inputAuthCode.toLocaleLowerCase(), state.authCode)

      if (state.inputAuthCode.toLocaleLowerCase() !== state.authCode) {
        document.getElementById('loginAuthCode')?.click()
        message.error(state.inputAuthCode ? '验证码错误，请重新输入！' : '请输入验证码！')
        state.inputAuthCode = ''
        return
      }

      store
        .dispatch('login/LOGIN', {
          userName: state.platFormUserName,
          userPass: state.platFormUserPass
        })
        .then(res => {
          /* 账号密码登录跳转方式 */
          router.push('/CBC')
        })
        .catch(err => {
          document.getElementById('loginAuthCode')?.click()
        })
    }

    onMounted(() => {
      // DrawAuthCode('login-authCode')
    })
    return () => (
      <CForm
        class='w-318 mt-21 mx-auto'
        v-model={[state, 'model']}
        onFormSubmit={handleFormFinish}
        onFormReset={() => {}}
        labelCol={{
          span: 0
        }}
        wrapperCol={{
          span: 24
        }}
      >
        <a-form-item name='platFormUserName' class='mb-36'>
          <a-input
            v-model={[state.platFormUserName, 'value', ['trim']]}
            class='h-40 pl-12 rounded-2 text-16'
            placeholder='输入用户名或者手机号'
          >
            {{
              prefix: () => <IconImg imgName='login-user' class='w-16 h-16'></IconImg>
            }}
          </a-input>
        </a-form-item>
        <a-form-item name='platFormUserPass' class='mb-36'>
          <a-input
            v-model={[state.platFormUserPass, 'value', ['trim']]}
            class='pl-12 h-40 rounded-2 text-16'
            placeholder='密码'
            type='password'
          >
            {{
              prefix: () => <IconImg imgName='login-password' class='w-16 h-16'></IconImg>
            }}
          </a-input>
        </a-form-item>
        <div class='flex items-center mb-36'>
          <a-input
            v-model={[state.inputAuthCode, 'value', ['trim']]}
            class='flex-1 pl-12 h-40 rounded-2 text-1 mr-14'
            placeholder='验证码'
          >
            {{
              prefix: () => <IconImg imgName='login-authCode' class='w-16 h-16'></IconImg>
            }}
          </a-input>
          {/* <canvas id='login-authCode' class='w-98 h-40 rounded-2'></canvas> */}
          <CAuthCode
            id='loginAuthCode'
            contentWidth={98}
            contentHeight={40}
            onAuthCodeChange={authCode => {
              state.authCode = authCode.toLocaleLowerCase()
              if (process.env.NODE_ENV !== 'production') {
                state.inputAuthCode = authCode.toLocaleLowerCase()
              }
            }}
          ></CAuthCode>
        </div>
        <a-form-item>
          <a-button
            type='primary'
            class='w-full h-40 rounded flex justify-center items-center'
            html-type='submit'
          >
            <CnNormalSpan class='text-white text-16'>登录</CnNormalSpan>
          </a-button>
        </a-form-item>
      </CForm>
    )
  }
})

/**微信扫码登录 */
const WxLogin = defineComponent({
  props: {
    show: Boolean
  },
  setup(props, ctx) {
    const {router, store} = useGlobalAPI()

    const {connectWebSocket, closeWebSocket, sendMessage, openHeartBeat, refreshWebSocket} =
      useWebSocket<
        Omit<WebSocketReplyData, 'devGId'> & {address: string},
        Omit<WebSocketSendData, 'devGId'> & {address: string}
      >({
        onopen(e) {
          sendMessage({
            address: '',
            msg: '',
            result: '',
            commandType: 'send',
            data: '',
            command: 'connect_WEB'
          })
        },
        onmessage(data) {
          console.log(data)
          if (data.result === 'success') {
            switch (data.command) {
              case 'connect_WEB':
                openHeartBeat({
                  address: '',
                  msg: '',
                  result: '',
                  commandType: 'send',
                  data: '',
                  command: 'heartBeat_WEB'
                })
                drawQrcode(
                  `https://d.lohand.com:10001/weixin/miniprogram?qrcodeType=webScanLogin&webScanLogin_address=${data.address}`
                )
                break
              case 'wxScan_WEB':
                store
                  .dispatch('login/WXSCANLOGIN', {
                    userName: data.data.userName,
                    userWeichatId: data.data.userWeichatId
                  })
                  .then(res => {
                    if (res) {
                      router.push('/CBC')
                    }
                  })
                break
              default:
                console.log('websocket onmessage 未知指令')
                break
            }
          }
        }
      })

    const {drawQrcode, isOvertime} = useQrcode({
      id: 'login_wxqrcode',
      toCanvasOption: {
        width: 244
      }
    })

    watch(
      () => props.show,
      n => {
        if (n) {
          connectWebSocket()
        } else {
          closeWebSocket()
        }
      },
      {immediate: true}
    )

    watch(
      () => isOvertime.value,
      n => {
        if (n) {
          closeWebSocket()
        }
      },
      {immediate: true}
    )

    onUnmounted(() => {
      closeWebSocket()
    })
    return () =>
      props.show ? (
        <div class='relative'>
          {isOvertime.value ? (
            <div class='absolute top-0 left-0 w-full h-full z-10'>
              <div class='w-full h-full bg-white opacity-95'></div>
              <i
                class='absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 iconfont icon-shuaxin text-36 z-20 cursor-pointer'
                onClick={() => refreshWebSocket()}
              ></i>
            </div>
          ) : null}
          <canvas class='mx-auto' id='login_wxqrcode'></canvas>
          <CnNormalP class='text-14 text-4xText text-center'>使用微信小程序扫码登录</CnNormalP>
        </div>
      ) : null
  }
})

export default defineComponent({
  name: 'login',
  setup() {
    const state = reactive({
      activeKey: '1'
    })

    onMounted(() => {
      // new Ckline({svgId: 'cSvg'})
    })
    return () => (
      <div
        class='login w-full h-full relative bg-mai bg-loginPc'
        style={{
          backgroundSize: '100%',
          backgroundPosition: 'left top'
        }}
      >
        <div class='w-490 h-590 px-48 rounded-6 overflow-hidden bg-white absolute top-1/2 right-8/100 transform -translate-y-1/2'>
          <div class='flex flex-col justify-center  items-center'>
            <div class='flex justify-center items-center mt-40'>
              <IconImg imgName='LOGO' class='w-32 h-32 mr-10'></IconImg>
              <CnBoldSpan class='text-32'>恒蓝云</CnBoldSpan>
            </div>
            <CnNormalP class='text-12 tracking-2 text-center'>Constant Blue Cloud</CnNormalP>
            <CImage imgName='slogan' class='w-245 h-17 inline-block mt-11'></CImage>
          </div>
          <div style='padding-top:60px'>
            <UserAccountLogin></UserAccountLogin>
          </div>

          {/* <a-tabs
            class='w-full mt-48 px-20'
            v-model={[state.activeKey, 'activeKey']}
            destroyInactiveTabPane={false}
          >
            <a-tab-pane key='1'>
              {{
                default: () => <UserPhoneLogin></UserPhoneLogin>,
                tab: () => {
                  return state.activeKey === '1' ? (
                    <CnBoldSpan class={`text-xText  text-20`}>手机登录</CnBoldSpan>
                  ) : (
                    <CnNormalSpan class={`text-6xText text-20`}>手机登录</CnNormalSpan>
                  )
                }
              }}
            </a-tab-pane>
            <a-tab-pane key='2'>
              {{
                default: () => <UserAccountLogin></UserAccountLogin>,
                tab: () => {
                  return state.activeKey === '2' ? (
                    <CnBoldSpan class={`text-xText  text-20`}>账号登录</CnBoldSpan>
                  ) : (
                    <CnNormalSpan class={`text-6xText text-20`}>账号登录</CnNormalSpan>
                  )
                }
              }}
            </a-tab-pane>
            <a-tab-pane key='3'>
              {{
                default: () => <WxLogin show={state.activeKey === '3'}></WxLogin>,
                tab: () => {
                  return state.activeKey === '3' ? (
                    <CnBoldSpan class={`text-xText  text-20`}>扫码登录</CnBoldSpan>
                  ) : (
                    <CnNormalSpan class={`text-6xText text-20`}>扫码登录</CnNormalSpan>
                  )
                }
              }}
            </a-tab-pane>
          </a-tabs> */}
        </div>
      </div>
    )
  }
})
